package save

import (
	"bufio"
	"image"
	"image/color"
	"image/png"
	"os"
)

func SaveInPNG(length, width int, sdf [][]float64, address string) error {
	img := image.NewRGBA(image.Rect(0, 0, length, width))
	for i := 0; i < width; i++ {
		for j := 0; j < length; j++ {
			v := uint16(ndc2pixed(sdf[i][j]) * 65535)
			img.Set(j, i, color.RGBA64{R: v, G: v, B: v, A: 65535})
		}
	}
	return save(address, img)
}

func save(address string, img image.Image) error {
	if address == "" {
		address = "./unknow.png"
	}
	file, err := os.OpenFile(address, os.O_CREATE|os.O_WRONLY, 0777)
	if err != nil {
		return err
	}
	defer file.Close()
	b := bufio.NewWriter(file)
	err = png.Encode(b, img)
	if err != nil {
		return err
	}
	err = b.Flush()
	if err != nil {
		return err
	}
	return nil
}

// ndc空间转为像素空间 [-1,1]->[0,1]
func ndc2pixed(num float64) float64 {
	return (num + 1) / 2
}
